/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.web.controller;

import cc.altius.domain.Role;
import cc.altius.domain.User;
import cc.altius.service.UserService;
import cc.altius.utils.LogUtils;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

/**
 *
 * @author Akil Mahimwala
 */
@Controller
@RequestMapping("/admin/userEdit.htm")
@SessionAttributes("user")
public class EditUserController {

    @Autowired
    private UserService userService;

    @ModelAttribute("roleList")
    public List<Role> populateRoleList() {
        return this.userService.getRoleList();
    }

    @RequestMapping(method = RequestMethod.GET)
    public String showEditUserForm(@RequestParam(value = "userId", required = true) int userId, ModelMap model) {
        User user = this.userService.getUserByUserId(userId);
        model.addAttribute("user", user);
        return "/admin/userEdit";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(@ModelAttribute("user") User user, Errors errors, SessionStatus sessionStatus) {
        User newUser = this.userService.getUserByUsername(user.getUsername());
        if (newUser!=null && newUser.getUserId()!=user.getUserId()) {
            errors.reject("username", "msg.duplicateUser");
            return "/admin/userEdit";
        }
        try {
            this.userService.updateUser(user);
            sessionStatus.setComplete();
            return "redirect:userList.htm?msg=msg.userUpdatedSuccessfully";
        } catch (Exception e) {
            LogUtils.systemLogger.info(e);
            errors.reject("username", "msg.userError");
            return "/admin/userEdit";
        }
    }
    
    

}
